onload = () => {
    loadCSS("../css/fontello.css", "bootstrap5-icon");
    loadCSS("../css/bootstrap5.min.css", "bootstrap5");
    loadCSS("../css/common.css", "common");
    loadScript("../js/bootstrap5.bundle.min.js")
        .then(() => loadScript("../js/crud.js")).then(() => {
        let pagination = new Pagination(loadDetail, document.getElementById("subPagination"))
        pagination.init();
        let detailQuery = {};
        let arReportOperator = new Crud({
            module: "arStatement",
            hasCheckbox: true,
            iterators: [],
            extendAttribute: [{name: "updatedBy", type: "userById"}],
            opsButton: [{
                caption: "Create Report",
                "action": "modal",
                "param": "#dateRangeModal",
                class: "btn btn-primary",
                commit: form => {
                    let view = true;
                    form.elements["view"].forEach(i => {
                        if (i.checked) view = i.value
                    });
                    let url = `/ar/createStatement?`;
                    if (form.elements["startDate"].value !== "" && form.elements["endDate"].value !== "")
                        url += `from=${form.elements["startDate"].value + "T00:00:00"}&to=${form.elements["endDate"].value + "T00:00:00"}`;
                    if (form.elements["billFromDate"].value !== "" && form.elements["billToDate"].value !== "")
                        url += `&billFrom=${form.elements["billFromDate"].value + "T00:00:00"}&billTo=${form.elements["billToDate"].value + "T00:00:00"}`;
                    url += `&view=${view}`;
                    ajax(url).then(data => {
                        showToast(`Upload successful: ${JSON.stringify(data.data)}`, "primary");
                        loadData();
                        let modalElement = document.getElementById("dateRangeModal");
                        const modal = bootstrap.Modal.getInstance(modalElement)
                            || new bootstrap.Modal(modalElement);
                        modal.hide();
                    })
                }
            }],
            rowBtn: ["delete"],
            search: [],
            listField: [{"caption": "ID", "field": "arStatementId"},
                {caption: "Type", "field": "type"},
                {caption: "From", "field": "invoiceTimeFrom", format: str => subString(str, 0, 10)},
                {caption: "To", "field": "invoiceTimeTo", format: str => subString(str, 0, 10)},
                {caption: "Bill From", "field": "billTimeFrom", format: str => subString(str, 0, 10)},
                {caption: "Bill To", "field": "billTimeTo", format: str => subString(str, 0, 10)},
                {caption: "Waybill Count", "field": "waybillCount"},
                {caption: "Revenue", "field": "revenue", format: v => v / 100},
                {caption: "Cost", "field": "cost", format: v => v / 100},
                {caption: "Profit", "field": "profit", format: v => v / 100},
                {caption: "Profit Margin", "field": i => (i.profit * 100 / i.revenue).toFixed(2), format: v => v + "%"},
                {caption: "UpdateTime", "field": "createTime", format: str => subString(str, 0, 10)},
                {caption: "UpdatedBy", "field": "updatedBy_userById.userName"}],
            rowEvent: function (e, item, tr, outer) {
                detailQuery.arStatementId = item.arStatementId;
                loadDetail();
                canvas.show();
            },
            subTable: [{
                name: "chargeTable",
                tableId: "chargeTable",
                listField: [{"caption": "Tracking#", "field": "trackingNo"},
                    {"caption": "Customer", "field": "customer"},
                    {"caption": "Earliest Bill Date", "field": "earliestBillDate"},
                    {"caption": "Carrier", "field": "carrier"},
                    {"caption": "Revenue", "field": "revenue", format: str => str / 100},
                    {"caption": "Cost", "field": "cost", format: str => str / 100},
                    {"caption": "Profit", "field": "profit", format: str => str / 100},
                    {
                        "caption": "Profit Margin",
                        "field": (i) => (i.profit * 100 / i.revenue).toFixed(2),
                        format: str => str + "%"
                    },
                ], opsBtn: [{
                    caption: "Export",
                    class: "btn btn-primary",
                    callback: () => {
                        ajax(`/ar/statement/export`, {method: "POST", body: {data: detailQuery}}, function (data) {
                            if (data.data) {
                                showToast(`Click to <a href='${contentPath + "/file/download/" + data.data}'>download</a>`,-1);
                            }
                        });
                    }
                }],
            }],
            editFields: [
                {"name": "code", "placeHolder": "code", "required": "required"},
                {"name": "pk", "placeHolder": "PK in cargo wise", "required": "required"},
                {caption: "Full Name:", "name": "fullname", "placeHolder": "Full name", "required": "required"}
            ]
        });
        arReportOperator.setCrudLink("list","/ar/list");
        arReportOperator.setCrudLink("delete","/ar/delete");
        arReportOperator.init();
        function loadData() {
            arReportOperator.loadData();
        }

        function loadDetail() {
            let data = {pageSize: pagination.getPageSize(),
                "offset": (pagination.getPage() - 1) * pagination.getPageSize()
            };
            data.data = detailQuery;
            ajax("/ar_statement_detail/list", {method: "POST", body: data}, data => {
                arReportOperator.subTable("chargeTable").load(data.data);
                pagination.setTotalRecord(data.count)
            })
        }
        const canvas = new bootstrap.Modal(document.getElementById('subTable'));
    }).catch((err) => console.error(err));
}



